const mysql = require('mysql2/promise');
const { logger } = require('../utils/logger');
require('dotenv').config();

// 检查是否使用模拟数据库
if (process.env.USE_MOCK_DB === 'true' || ((!process.env.NODE_ENV || process.env.NODE_ENV === 'development') && !process.env.DB_PASSWORD)) {
  logger.info('使用模拟数据库进行开发测试');
  module.exports = require('./mockDatabase');
  return;
}

// 数据库连接配置
const dbConfig = {
  host: process.env.DB_HOST || 'localhost',
  port: process.env.DB_PORT || 3306,
  user: process.env.DB_USER || 'root',
  password: process.env.DB_PASSWORD || '',
  database: process.env.DB_NAME || 'cu_mr_bull_db',
  charset: 'utf8mb4',
  timezone: '+08:00', // 新加坡时区
  // 连接池配置
  connectionLimit: 10,
  queueLimit: 0
};

// 如果提供了 SSL CA 证书，则开启 TLS
if (process.env.DB_SSL_CA) {
  const fs = require('fs');
  try {
    const ca = fs.readFileSync(process.env.DB_SSL_CA);
    dbConfig.ssl = { ca };
    logger.info('已启用数据库 TLS 连接');
  } catch (e) {
    logger.warn('未能读取 DB_SSL_CA 指定的文件，继续以非TLS方式连接:', e.message);
  }
}

// 创建连接池
const pool = mysql.createPool(dbConfig);

// 测试数据库连接
const testConnection = async () => {
  try {
    const connection = await pool.getConnection();
    logger.info('数据库连接成功');
    connection.release();
    return true;
  } catch (error) {
    return false;
  }
};

// 执行查询的通用方法
const query = async (sql, params = []) => {
  try {
    const [rows, fields] = await pool.execute(sql, params);
    // 对于INSERT/UPDATE/DELETE操作，返回ResultSetHeader
    // 对于SELECT操作，返回rows数组
    if (sql.trim().toUpperCase().startsWith('INSERT') || 
        sql.trim().toUpperCase().startsWith('UPDATE') || 
        sql.trim().toUpperCase().startsWith('DELETE')) {
      return rows; // ResultSetHeader包含insertId, affectedRows等
    }
    return rows; // SELECT查询返回数据行
  } catch (error) {
    throw error;
  }
};

// 新增：execute 方法，保持与 mysql2 一致的返回结构 [rows, fields]
const execute = async (sql, params = []) => {
  try {
    const [rows, fields] = await pool.execute(sql, params);
    return [rows, fields];
  } catch (error) {
    throw error;
  }
};

// 执行事务的方法
const transaction = async (callback) => {
  const connection = await pool.getConnection();
  try {
    await connection.beginTransaction();
    const result = await callback(connection);
    await connection.commit();
    return result;
  } catch (error) {
    await connection.rollback();
    throw error;
  } finally {
    connection.release();
  }
};

// 关闭连接池
const closePool = async () => {
  try {
    await pool.end();
    logger.info('数据库连接池已关闭');
  } catch (error) {
    logger.error('关闭数据库连接池时出错:', error);
  }
};

// 优雅关闭处理
process.on('SIGINT', async () => {
  logger.info('正在关闭数据库连接...');
  await closePool();
  process.exit(0);
});

process.on('SIGTERM', async () => {
  logger.info('正在关闭数据库连接...');
  await closePool();
  process.exit(0);
});

module.exports = {
  pool,
  query,
  execute,
  transaction,
  testConnection,
  closePool,
  getConnection: async () => {
    return pool.getConnection();
  }
};